package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @ClassNameCommonController
 * @Description TODO
 * @Author钰玟
 * @Date2025/2/13 下午2:19
 * @Version 1.0
 **/

/*
通用接口的 控制层
* */
@RestController
@RequestMapping("/admin/common")
@Api(tags = "通用接口")
@Slf4j
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;
    /**
     * 上传文件
     * @param file 文件
     * @return Result<String>
     */
    @PostMapping("/upload")
    @ApiOperation(value = "上传文件")
    public Result<String> uploadFile(MultipartFile file){
        log.info("上传文件,{}",file);
        //截取文件名后缀

//        String suffix = file.getOriginalFilename().split(".")[1];
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        //前缀
        String prefix = UUID.randomUUID().toString();
        //拼接文件名
        String fileName = prefix + suffix;
        //通过UUID生成文件名 防止文件名重复
        try {
            //请求路径
            String uploadPath = aliOssUtil.upload(file.getBytes(), fileName);
            return Result.success(uploadPath);
        } catch (IOException e) {
            log.error("上传文件失败:{}",e);
//            e.printStackTrace();
        }
        //使用常量类封装错误信息 兜底处理 防止后续改动 影响代码逻辑
        return Result.error(MessageConstant.UPLOAD_FAILED);
    }


}
